package com.cxh.supermarket.im;

import cn.hutool.core.util.ObjectUtil;
import java.util.Date;
import java.util.Map;

/**
 * 功能描述:
 *
 * @author zxl
 * @since 2024/4/24
 */
public class NotificationUtil {
  /**
   * 获取模版实体类
   * 例子在ServiceTest.testImSend()
   *
   * @param businessName 业务名称 {@link NotificationEnum}的业务名称
   * @param contentMap   文案内容KV {@link NotificationEnum}对应的文案内容中的${xx}作为map的key
   * @param extendData   扩展数据
   * @param isOpen       是否弹框
   * @return Notification
   */
  public static Notification getNotification(String businessName, Map<String, String> contentMap, Object extendData, boolean isOpen) {
    Notification notification = new Notification();
    if (ObjectUtil.isNotNull(businessName)) {
      NotificationEnum notificationEnum = NotificationEnum.of(businessName);

      notification.setCategory(notificationEnum.getCategory());
      notification.setTitle(notificationEnum.getTitle());
      //解析占位符
      String content = parseTemplate(notificationEnum.getContent(), contentMap);

      notification.setContent(content);
      notification.setTimestamp(new Date());
      notification.setPushLevel(notificationEnum.getPushLevel());
      notification.setExtendData(extendData);
      notification.setOpen(isOpen);
      return notification;
    }
    return null;

  }

  public static String parseTemplate(String template, Map<String, String> map) {
    if (map == null || map.isEmpty()) {
      return template; // 如果map为空或者map中没有键值对，直接返回原始模板字符串
    }
    // 检查模板中是否包含占位符
    if (!template.contains("${")) {
      return template; // 如果模板中没有占位符，直接返回原始模板字符串
    }

    String parsedMessage = template;

    for (Map.Entry<String, String> entry : map.entrySet()) {
      String placeholder = "${" + entry.getKey() + "}";
      String value = entry.getValue();

      parsedMessage = parsedMessage.replace(placeholder, value);
    }

    return parsedMessage;
  }
}
